import aiohttp
import asyncio
import json
from videofilesystem import  create_nested_folders
import requests


import subprocess
import threading
from typing import Optional, Callable

# def async_scp_transfer(
#     source: str,
#     dest_host: str,
#     dest_dir: str,
#     callback: Optional[Callable[[bool, str], None]] = None,
# ) -> None:
#     """免密环境专用异步SCP传输"""
    
def _scp(source:str,dest_host:str,dest_dir:str):
    try:
        # 直接构造目标地址（假设host已包含用户名）
        print("in")
        cmd = ["scp", source, f"{dest_host}:{dest_dir}"]
        print("cmd: ",cmd)
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        stdout, stderr = process.communicate()

    except Exception as e:
        if callback: callback(False, f"Fatal error: {str(e)}")

def _mv(source:str, dest_dir:str):
    try:
        # 直接构造目标地址（假设host已包含用户名）
        print("in")
        cmd = ["cp", source, f"{dest_dir}"]
        print("cmd: ",cmd)
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        stdout, stderr = process.communicate()
        
    except Exception as e:
        if callback: callback(False, f"Fatal error: {str(e)}")

# threading.Thread(target=_mv, args=("/data/mn4/chunk_0000/chunk_0000.mp4","/data/processvideo"),  daemon=True).start()
# print("1")
# threading.Thread(target=_scp, args=("/data/mn4/chunk_0000/chunk_0000.mp4", "linaro@192.168.0.188", "/data"),  daemon=True).start()
# print("2")
# threading.Thread(target=_scp, args=("/data/mn4/chunk_0000/chunk_0000.mp4", "linaro@192.168.0.188", "/data/tmp"),  daemon=True).start()
# print("3")
# import time
# time.sleep(10)



async def call_run_cpp_api_async(host='localhost', port=6000, 
                                send_info=False, camera_name='chunk_0000', 
                                video_name='chunk_0000',  image_base_index = 0):
    """
    异步调用 /api/run-cpp 接口
    
    参数和返回值同同步版本
    """
    url = f"http://{host}:{port}/api/run-cpp"
    headers = {'Content-Type': 'application/json'}
    payload = {
        'send_info': send_info,
        'camera_name': camera_name,
        'video_name': video_name,
        "image_base_index_":image_base_index
    }
    
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(
                url,
                headers=headers,
                data=json.dumps(payload),
                timeout=aiohttp.ClientTimeout(total=30)
            ) as response:
                
                data = await response.json()
                return {
                    'status_code': response.status,
                    'data': data,
                    'success': response.status == 202
                }
                
    except Exception as e:
        return {
            'status_code': 500,
            'error': str(e),
            'success': False
        }

async def main():
    result = await call_run_cpp_api_async(
        host='192.168.0.186',
        send_info=False
    )
    print(result)

def increment_counter_sync(base_url="http://localhost:5000"):
        """
        同步方式调用/increment_count接口
        
        参数:
            base_url: 服务基础地址
            
        返回:
            tuple: (是否成功, 当前计数或错误信息)
        """
        url = f"{base_url}/increment_count"
        try:
            response = requests.post(url)
            if response.status_code == 200:
                data = response.json()
                return True, data['completed_count']
            else:
                return False, f"请求失败，状态码: {response.status_code}"
        except Exception as e:
            return False, f"请求异常: {str(e)}"


def stop_cpp_process(ip="localhost"):
    url = "http://"+ ip + ":6000/api/stop"
    try:
        # 发送 POST 请求（可携带或不携带 JSON 数据）
        response = requests.post(url, json={"action": "stop"})
        response.raise_for_status()  # 检查HTTP错误
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        return None


if __name__ == '__main__':
    # create_nested_folders(folder1="chunk_0000", folder2="chunk_0000")
    # asyncio.run(call_run_cpp_api_async(
    #     host='192.168.0.188',
    #     send_info=False
    # ))
    # # test_increment_counter()
    # import time 
    # time.sleep(15)
    # print("stop")
    # stop_cpp_process(ip="192.168.0.188")

    # result = upload_video_with_name(
    #     video_path="/data/mn4/chunk_0000/chunk_0000.mp4",
    #     video_name="chunk_0000",
    #     server_url="http://192.168.0.188:6000",
    #     timeout=600  # 10分钟超时
    # )
    # print(result)

    async_scp_transfer(
        source="/data/mn4/chunk_0000/chunk_0000.mp4",
        dest_host="linaro@192.168.0.188",
        dest_dir="/data/processvideo"
    )
